package com.itcast.ixun.fragment;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;
import com.itcast.ixun.R;
import com.itcast.ixun.adapter.ItemAdapter;
import com.itcast.ixun.models.HomeModels;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class HomeHotFragment extends Fragment {

    private RecyclerView recyclerView;
    private ItemAdapter adapter;
    private HomeModels homeModels;

    private String url = "http://app.lerays.com/api/stream/rec/list?pubtime=0&cate_sign=null";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_home_hot, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        recyclerView = (RecyclerView) getView().findViewById(R.id.recyclerView_hot);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        initData();
    }

    private void initData() {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Gson gson = new Gson();
                homeModels = gson.fromJson(result, HomeModels.class);
                if (!homeModels.equals("")) {
                    handler.sendEmptyMessage(1);
                }
            }
        });

    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                adapter = new ItemAdapter(homeModels.getData().getList(), getActivity());
                recyclerView.setAdapter(adapter);
            }

        }
    };
}
